#include "mainwindow.h"
#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include <QPixmap>
#include <QPainter>

#include <QTimer>

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qDebug() << "mainWindowThreadID:" << QThread::currentThreadId();

    ui->setupUi(this);
    setWindowIcon(QIcon(":/pic/box.gif"));  //设置窗口图标
    setWindowTitle(tr("俄罗斯方块"));
    setFixedSize(this->width(), this->height());  //设置窗体不可伸缩

    myThread = new QThread();
    myThread->start();  //开始子线程
    data = new Data();
    data->moveToThread(myThread);
    connect(myThread, SIGNAL(finished()), data, SLOT(deleteLater()));
    connect(this, SIGNAL(dataStart()), data, SLOT(slot_init()));
    myThread->start();  //开始子线程
    emit dataStart();   //发送信号, 让线程开始执行初始化


    int gameWidget_x = ui->gameWidget->geometry().x();
    int gameWidget_y = ui->gameWidget->geometry().y();
    for (int y=0; y<20; y++) {
        for (int x=0; x<10; x++) {
            QLabel *label = new QLabel(ui->gameWidget);
            label->setGeometry(gameWidget_x + x*15, gameWidget_y + y*15, 14, 14);
            label->setStyleSheet("background-color:white");
            gameLableList.append(label);
        }
    }
    ui->gameWidget->resize(15*13, 15*21);

    int nextBlockWgt_x = ui->nextBlockWidget->geometry().x();
    int nextBlockWgt_y = ui->nextBlockWidget->geometry().y();
    for (int y=0; y<4; y++) {
        for (int x=0; x<4; x++) {
            QLabel *label = new QLabel(ui->nextBlockWidget);
            label->setGeometry(nextBlockWgt_x + x*15, nextBlockWgt_y +y*15, 14, 14);
            label->setStyleSheet("background-color:white");
            nextBlockList.append(label);
        }
    }
    ui->nextBlockWidget->resize(15*6, 15*6);

//    ui->iBtn_game->setText(tr("开始游戏"));
//    connect(ui->iBtn_game, SIGNAL(clicked()), &data, SLOT(slot_gameBegin()));

    connect(data, SIGNAL(updateUi()), this, SLOT(slot_updateUi()));
//    qRegisterMetaType<dir_t>("dir_t"); //注册元类型
//    connect(this, SIGNAL(processKeyEvent(dir_t)), data, SLOT(slot_processKeyEvent(dir_t)), Qt::DirectConnection);
    qRegisterMetaType<dir_t>("dir_t"); //注册元类型
    connect(this, SIGNAL(processKeyEvent(dir_t)), data, SLOT(slot_processKeyEvent(dir_t)));

    connect(data, SIGNAL(gameOver()), this, SLOT(slot_gameOver()));
    connect(this, SIGNAL(gameBegin()), data, SLOT(slot_gameBegin()));

    action_newGame = new QAction(tr("新游戏"), this);
    action_newGame->setShortcut(tr("Ctrl+N"));

    action_help = new QAction(tr("帮助"), this);
    action_help->setShortcut(tr("ctrl+P"));

    action_about = new QAction(tr("关于"), this);

    connect(action_newGame, SIGNAL(triggered()), this, SLOT(slot_newGame()));
    connect(action_help, SIGNAL(triggered()), this, SLOT(slot_showHelp()));
    connect(action_about, SIGNAL(triggered()), this, SLOT(slot_showAbout()));

    showMenuBar();  //设置菜单栏
    QString str = QString("分数: %1").arg(0);
    ui->oLabel_grade->setText(str); //设置分数
    ui->oLabel_grade->setStyleSheet("font-size:16px");

    ui->iBtn_beginAndEnd->setText(tr("开始新游戏"));
    ui->iBtn_pause->setEnabled(false);
}
MainWindow::~MainWindow()
{
    myThread->quit();   //开始销毁子线程(销毁时间由系统调度决定)
    myThread->wait();   //等待子线程被系统销毁
    delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_1){  //开始
        emit processKeyEvent(BEGIN);
    } else if (event->key() == Qt::Key_3) { //暂停/继续
        emit processKeyEvent(PAUSE);
    }
    if (data->flag_gameRunning == false) {
        return ;
    }
    if (event->key() == Qt::Key_A) {
        emit processKeyEvent(LEFT);
    } else if (event->key() == Qt::Key_D){
        emit processKeyEvent(RIGHT);
    } else if (event->key() == Qt::Key_W) {    //变形
        emit processKeyEvent(CHANGE);
    } else if (event->key() == Qt::Key_2){  //结束
        emit processKeyEvent(END);
    } else if (event->key() == Qt::Key_S) {  //加快下降速度
        emit processKeyEvent(QUICK_DOWN);
    } else {
        qDebug() << event->text();
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    //qDebug() << "key Release Event! : " << event->text();
//    if (event->key() == Qt::Key_1){  //开始
//        emit processKeyEvent(BEGIN);
//    } else if (event->key() == Qt::Key_3) { //暂停/继续
//        emit processKeyEvent(PAUSE);
//    }
//    if (data->flag_gameRunning == false) {
//        return ;
//    }
//    if (event->key() == Qt::Key_A) {
//        emit processKeyEvent(LEFT);
//    } else if (event->key() == Qt::Key_D){
//        emit processKeyEvent(RIGHT);
//    } else if (event->key() == Qt::Key_W) {    //变形
//        emit processKeyEvent(CHANGE);
//    } else if (event->key() == Qt::Key_2){  //结束
//        emit processKeyEvent(END);
//    } else if (event->key() == Qt::Key_S) {  //加快下降速度
//        emit processKeyEvent(QUICK_DOWN);
//    } else {
//        qDebug() << event->text();
//    }
}

//设置菜单栏
void MainWindow::showMenuBar()
{
    mainMenu = menuBar()->addMenu(tr("选项"));
    mainMenu->addAction(action_newGame);
    mainMenu->addAction(action_help);

    aboutMenu = menuBar()->addMenu(tr("关于"));
    aboutMenu->addAction(action_about);
}

void MainWindow::slot_updateUi()
{
    qDebug() << "mainWindowUpdateUi";
    QString str = QString("分数: %1").arg(data->grade);
    ui->oLabel_grade->setText(str); //设置分数
    for (int y=0; y<20; y++) {
        for (int x=0; x<10; x++) {
            if (data->gameData[y][x]) {
                gameLableList.at(y*10 + x)->setStyleSheet("background-color:black");
            } else {
                gameLableList.at(y*10 + x)->setStyleSheet("background-color:white");
            }

        }
    }
    for (int y=0; y<4; y++) {
        for (int x=0; x<4; x++) {
            if (data->currentBlock[y][x]) {
                if (data->current_y+y < 0){  //需要在窗口中显示
                    continue;
                }
                gameLableList.at(data->current_x+x + (data->current_y+y)*10)->setStyleSheet("background-color:black");
            }
        }
    }
    for (int y=0; y<4; y++) {
        for (int x=0; x<4; x++) {
            if (data->nextBlock[y][x]) {
                nextBlockList.at(y*4 + x)->setStyleSheet("background-color:black");
            } else {
                nextBlockList.at(y*4 + x)->setStyleSheet("background-color:white");
            }
        }
    }
}
//结束游戏
void MainWindow::slot_gameOver()
{
    QMessageBox::warning(this, tr("警告"), tr("Game Over!"));
}
//显示帮助页面
void MainWindow::slot_showHelp()
{
    QString msg;
    msg += "按键1: 启动一个新游戏 \n";
    msg += "按键2: 结束该游戏 \n";
    msg += "按键3: 暂停游戏\n";
    msg += "'a','d': 控制方块左右移动\n";
    msg += "'w': 方块变形\n";
    msg += "'s': 当前方块快速下落";

    QMessageBox::information(this, tr("帮助"), msg);
}
//新游戏
void MainWindow::slot_newGame()
{
    emit processKeyEvent(BEGIN);
}
//显示关于
void MainWindow::slot_showAbout()
{
    QString msg = "本游戏使用Qt5.3.2编写. 使用请遵循GPL. \n     作者: zhaoyongCNSX";
    QMessageBox::information(this, tr("关于"), msg);
}


void MainWindow::on_iBtn_beginAndEnd_clicked()
{
    static bool flag = true;
    if (flag) { //打开
        flag = false;
        ui->iBtn_beginAndEnd->setText(tr("结束游戏"));
        ui->iBtn_pause->setEnabled(true);
        emit processKeyEvent(BEGIN);
    } else {
        flag = true;
        ui->iBtn_beginAndEnd->setText(tr("开始新游戏"));
        ui->iBtn_pause->setEnabled(false);
        emit processKeyEvent(END);
    }
}

void MainWindow::on_iBtn_pause_clicked()
{
    emit processKeyEvent(PAUSE);
}
